package com.siterwell.push;

import com.amazonaws.services.iot.client.*;
import com.siterwell.push.service.IDeviceLogService;
import com.siterwell.push.service.IDeviceService;
import com.siterwell.push.util.ReadUtil.AWSIotUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class AWSIotServer {
    private static final String AwsTopic = "st/siterlink/from_gw/+";
    private static final AWSIotQos TopicQos = AWSIotQos.QOS0;

    private static AWSIotMqttClient awsIotClient;

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceLogService deviceLogService;

    public void run() throws AWSIotException {
        initClient();
        awsIotClient.connect();
        TopicListener topic = new TopicListener(AwsTopic, TopicQos,deviceLogService,deviceService);
        awsIotClient.subscribe(topic, true);
    }

    private static void initClient() {
        String clientEndpoint = AWSIotUtil.getConfig("clientEndpoint");
        String clientId = AWSIotUtil.getConfig("clientId");

        String certificateFile = AWSIotUtil.getConfig("certificateFile");
        String privateKeyFile = AWSIotUtil.getConfig("privateKeyFile");
        if (awsIotClient == null && certificateFile != null && privateKeyFile != null) {
            String algorithm = AWSIotUtil.getConfig("keyAlgorithm");

            AWSIotUtil.KeyStorePasswordPair pair = AWSIotUtil.getKeyStorePasswordPair(certificateFile, privateKeyFile, algorithm);

            awsIotClient = new AWSIotMqttClient(clientEndpoint, clientId, pair.keyStore, pair.keyPassword);
        }

        if (awsIotClient == null) {
            String awsAccessKeyId = AWSIotUtil.getConfig("awsAccessKeyId");
            String awsSecretAccessKey = AWSIotUtil.getConfig("awsSecretAccessKey");
            String sessionToken = AWSIotUtil.getConfig("sessionToken");

            if (awsAccessKeyId != null && awsSecretAccessKey != null) {
                awsIotClient = new AWSIotMqttClient(clientEndpoint, clientId, awsAccessKeyId, awsSecretAccessKey,
                        sessionToken);
            }
        }

        if (awsIotClient == null) {
            throw new IllegalArgumentException("Failed to construct client due to missing certificate or credentials.");
        }
    }


}
